<template>
  <div class="amap-picker">
    <div class="map-search-container">
      <div v-if="searchResults.length > 0" class="search-results">
        <div v-for="(item, index) in searchResults" :key="index" class="search-result-item" @click="useSearchResult(item)">
          {{ item.formattedAddress }}
        </div>
      </div>
    </div>
    <div class="amap-wrapper" ref="mapContainer" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ lng: null, lat: null })
  },
  address: {
    type: String,
    default: ''
  },
  amapKey: {
    type: String,
    default: '9c5a053254c95d14843efc080ac74f78'
  },
  amapSecurityCode: {
    type: String,
    default: '59173e03758c881beab7c813d3a25329'
  },
  width: {
    type: String,
    default: '500px'
  },
  height: {
    type: String,
    default: '300px'
  }
});
const emit = defineEmits(['update:modelValue', 'update:address']);

const mapContainer = ref(null);
const map = ref(null);
const marker = ref(null);
const searchAddress = ref('');
const searchResults = ref([]);
const address = ref(props.address);

// 加载高德地图脚本
function loadAMap() {
  return new Promise((resolve, reject) => {
    window._AMapSecurityConfig = { securityJsCode: props.amapSecurityCode };
    if (window.AMap) return resolve(window.AMap);
    const script = document.createElement('script');
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${props.amapKey}&plugin=AMap.Geocoder`;
    script.async = true;
    script.onload = () => resolve(window.AMap);
    script.onerror = (error) => reject(error);
    document.head.appendChild(script);
  });
}

function initMap() {
  if (!mapContainer.value) return;
  if (!window.AMap) {
    loadAMap().then(() => setTimeout(initMap, 500));
    return;
  }
  map.value = new AMap.Map(mapContainer.value, {
    zoom: 11,
    resizeEnable: true,
    center: [props.modelValue.lng || 116.397428, props.modelValue.lat || 39.90923]
  });
  if (props.modelValue.lng && props.modelValue.lat) {
    marker.value = new AMap.Marker({
      position: [props.modelValue.lng, props.modelValue.lat],
      map: map.value
    });
    map.value.setCenter([props.modelValue.lng, props.modelValue.lat]);
  }
  map.value.on('click', function(e) {
    if (marker.value) marker.value.setMap(null);
    marker.value = new AMap.Marker({
      position: [e.lnglat.getLng(), e.lnglat.getLat()],
      map: map.value
    });
    emit('update:modelValue', { lng: e.lnglat.getLng(), lat: e.lnglat.getLat() });
    getAddressFromLocation(e.lnglat.getLng(), e.lnglat.getLat());
  });
}

function getAddressFromLocation(lng, lat) {
  if (!window.AMap) return;
  const geocoder = new AMap.Geocoder({ city: '全国' });
  geocoder.getAddress([lng, lat], function(status, result) {
    if (status === 'complete' && result.info === 'OK') {
      if (result.regeocode && result.regeocode.formattedAddress) {
        address.value = result.regeocode.formattedAddress;
        emit('update:address', address.value);
      }
    } else {
      address.value = `坐标位置(${lng.toFixed(6)}, ${lat.toFixed(6)})`;
      emit('update:address', address.value);
    }
  });
}

function searchLocation() {
  if (!searchAddress.value || !window.AMap) return;
  AMap.plugin('AMap.Geocoder', function() {
    const geocoder = new AMap.Geocoder({ city: '全国' });
    geocoder.getLocation(searchAddress.value, function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        if (result.geocodes && result.geocodes.length > 0) {
          searchResults.value = result.geocodes;
          if (result.geocodes.length === 1) {
            useSearchResult(result.geocodes[0]);
          }
        } else {
          ElMessage.warning('未找到匹配的地址');
          searchResults.value = [];
        }
      } else {
        ElMessage.error('地址搜索失败');
        searchResults.value = [];
      }
    });
  });
}

function useSearchResult(item) {
  if (!map.value || !item || !item.location) return;
  const location = item.location;
  if (marker.value) marker.value.setMap(null);
  marker.value = new AMap.Marker({
    position: [location.lng, location.lat],
    map: map.value
  });
  map.value.setCenter([location.lng, location.lat]);
  map.value.setZoom(15);
  emit('update:modelValue', { lng: location.lng, lat: location.lat });
  address.value = item.formattedAddress;
  emit('update:address', address.value);
  searchResults.value = [];
}

watch(() => props.modelValue, (val) => {
  if (val && val.lng && val.lat && map.value) {
    if (marker.value) marker.value.setMap(null);
    marker.value = new AMap.Marker({
      position: [val.lng, val.lat],
      map: map.value
    });
    map.value.setCenter([val.lng, val.lat]);
  }
}, { deep: true });

onMounted(() => {
  loadAMap().then(() => {
    nextTick(() => {
      setTimeout(initMap, 500);
    });
  });
});

onUnmounted(() => {
  if (map.value) {
    try { map.value.destroy(); } catch (e) {}
    map.value = null;
  }
});
</script>

<style scoped>
.amap-picker {
}
.amap-wrapper {
  /* 由props控制宽高 */
  border: 1px solid #ddd;
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;
}
.map-search-container {
  margin-bottom: 10px;
  position: relative;
}
.search-results {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-height: 300px;
  overflow-y: auto;
  z-index: 999;
}
.search-result-item {
  padding: 10px 15px;
  cursor: pointer;
  border-bottom: 1px solid #ebeef5;
}
.search-result-item:hover {
  background-color: #f5f7fa;
}
.map-info {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}
</style> 